package com.jiazhong.boot.redis.random.controller;

import com.jiazhong.boot.commons.util.JsonResult;
import com.jiazhong.boot.commons.util.ResultTool;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@CrossOrigin
@RestController
@RequestMapping("/random")
public class RandomController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY = "RANDOM";

    @PostMapping("/add")
    public JsonResult add(String name) {
        stringRedisTemplate.opsForSet().add(KEY, name);
        return ResultTool.success("success");
    }

    @GetMapping("/all")
    public JsonResult find() {
        Set<String> members = stringRedisTemplate.opsForSet().members(KEY);
        return ResultTool.success(members);
    }

    private Set<String> randomSet = null;

    @GetMapping("/random")
    public JsonResult random() {
        if (this.randomSet == null) {
            Set<String> members = stringRedisTemplate.opsForSet().members(KEY);
            if (members.size() >= 16) {
                Set<String> distinctRandomMembers = stringRedisTemplate.opsForSet().distinctRandomMembers(KEY, 8);
                this.randomSet = distinctRandomMembers;
                return ResultTool.success(distinctRandomMembers);
            }
            this.randomSet = null;
            return ResultTool.fail(501, "人数不够");
        }
        return ResultTool.success(this.randomSet);
    }


}
